<template>
  <div class="user-manage">
    <div class="top-area filter-container">
      <el-input v-model="params.keywords" placeholder="请输入内容" style="width: 200px;" class="filter-item"
                @keyup.enter.native="searchClick"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchClick">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="addClick" v-if="btn['添加']">
        新增
      </el-button>
      <!-- <el-button size="small" type="primary"  class="btnblue" @click="searchClick">搜索</el-button> -->
      <!-- <el-button size="small" type="primary"  class="btnblue" @click="addClick">+ 新增</el-button> -->
    </div>
    <el-table ref="multipleTable" :data="tableData"
              border style="width: 100%"
              class="bill-table">
      <el-table-column
        prop="username"
        label="账号">
      </el-table-column>
      <el-table-column
        prop="name"
        label="名字">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="sexStr"
        label="性别">
      </el-table-column>
      <el-table-column prop="blockStr" label="状态">
      </el-table-column>

      <el-table-column
        label="操作"
        width="300"
        align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="updateClick(scope.row)" v-if="btn['修改']">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row)" v-if="btn['删除']">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="giveRole(scope.row)" v-if="btn['分配角色']">
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="params.total" :page.sync="params.pageNo" :limit.sync="params.pageSize"
                @pagination="searchClick"/>
    <el-dialog :title="type == 1?'添加用户':'编辑用户'" :visible.sync="dialogStatus" @closed="dalogClosed">
      <el-form :model="userObject" class="user" status-icon ref="ruleForm">
        <div class="dialog-form">
          <span class="from-title"><i class="from-title-i">*</i>账号</span>
          <el-form-item prop="username" class="el-form-userno">
            <el-input placeholder="30个字以内..." type="text" v-model="userObject.username"></el-input>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title"><i class="from-title-i">*</i>姓名</span>
          <el-form-item prop="name">
            <el-input placeholder="10个字以内..." type="text"
                      v-model="userObject.name"></el-input>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title">出生日期</span>
          <el-form-item>
            <el-date-picker
              v-model="userObject.birthday"
              value-format="yyyy-MM-dd hh:mm:ss"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title"><i class="from-title-i">*</i>密码</span>
          <el-form-item prop="name">
            <el-input placeholder="10个字以内..." type="text"
                      v-model="userObject.password"></el-input>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title"><i class="from-title-i">*</i>邮箱</span>
          <el-form-item prop="name">
            <el-input placeholder="10个字以内..." type="text"
                      v-model="userObject.email"></el-input>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title">电话</span>
          <el-form-item>
            <el-input type="text" maxlength="11" v-model="userObject.mobile"></el-input>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title">性别</span>
          <el-form-item>
            <el-radio-group v-model="userObject.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="dialog-form">
          <span class="from-title">状态</span>
          <el-form-item>
            <el-radio-group v-model="userObject.block">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <!-- <div class="dialog-form">
           <span class="from-title">身份类型</span>
           <el-form-item>
               <el-radio-group v-model="userObject.isuser">
                   <el-radio :label="0">商户</el-radio>
                   <el-radio :label="1">用户</el-radio>
               </el-radio-group>
           </el-form-item>
       </div> -->
      </el-form>
      <div slot="footer" class="dialog-footer dialog-form">
        <el-button class="bdnone" size="small" @click="dialogStatus = false">取消</el-button>
        <el-button size="small" type="primary" class="btnblue" @click="commitClick">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="337px"
      title="角色分配"
      :visible.sync="isShowDesignArea"
      @closed="treeClose">
      <div class="el-tree">
        <el-tree
          :data="allRoles"
          show-checkbox
          :props="defaultProps"
          node-key="id"
          accordion
          ref="tree"
          :filter-node-method="filterNode"
          :default-checked-keys="defaultChecks"
          @node-click="handleNodeClick">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="bdnone" size="small" @click="isShowDesignArea = false">取 消</el-button>
        <el-button size="small" class="btnblue" @click="roleSureClick">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import {userList, addUpdateUser, deleteUser, userRole} from "@/api/user.service.js";
  import {deleteRole, roleList, addUpdateRole} from "@/api/role.service.js";

  export default {
    name: 'user',
    components: {Pagination},
    props: {},
    data() {
      return {
        tableData: [],
        dialogTitle: '添加用户',
        // 1 代表添加用户  2代表编辑用户
        type: 1,
        dialogStatus: false,
        params: {
          keywords: "",
          pageNo: 1,
          pageSize: 20,
          total: 0,
        },
        userObject: {
          avatar: '',
          block: 0,//冻结(0：不冻结,1：冻结）
          email: '',
          mobile: '',
          // isuser:0,//用户(0：商户,1：管理员）
          name: '',
          password: '',
          sex: 1,//性别（1：男 2：女）
          username: '',
          birthday: ''
        },
        selectRow: {},
        allRoles: [],
        isShowDesignArea: false,
        defaultProps: {
          children: 'dists',
          label: 'name'
        },
        defaultChecks: []
      }
    },
    filters: {},
    watch: {},
    computed: {
      btn() {
        return JSON.parse(localStorage.getItem('btn'))[this.$route.name] || []
      }
    },
    mounted() {
      this.queryTableData()
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.nameStr.indexOf(value) !== -1;
      },
      treeClose() {
        this.isShowDesignArea = false
        this.allRoles = []
      },
      //点击非select框触发
      handleNodeClick(node) {

      },
      searchClick() {
        this.queryTableData()
      },
      handleCurrentChange(val) {
        this.queryTableData(val)
      },
      handleSizeChange(val) {
        this.params.pageSize = val
        this.queryTableData()
      },
      roleSureClick() {
        this.isShowDesignArea = false
        let roleList = this.$refs.tree.getCheckedNodes()
        let roleId = []
        roleList.map((item) => {
          roleId.push(item.id)
        })
        if (roleList.length == 0) {
          this.$message({type: 'warning', message: '请选择需要分配的角色'})
          return
        }
        let params = {
          roleId: roleId.join(','),
          userId: this.selectRow.id,
        }
        userRole(params).then((res) => {
          this.$message({type: 'success', message: '分配成功'})
          this.queryTableData()
        }).catch(error => {

        })
      },
      queryTableData() {
        this.tableData = []
        let {pageNo, pageSize} = this.params
        userList({pageNo, pageSize}).then((res) => {
          this.tableData = res.values
          this.tableData.map((item) => {
            if (item.sex == 1) {
              item.sexStr = '男'
            } else if (item.sex == 2) {
              item.sexStr = '女'
            }
            if (item.block) {
              item.blockStr = '禁用'
            } else {
              item.blockStr = '正常'
            }
          })
          this.params.total = res.total
        }).catch(error => {

        })
      },
      addClick(row) {
        this.type = 1
        this.selectRow = row
        this.userObject = {
          avatar: '',
          block: 0,//冻结(0：不冻结,1：冻结）
          email: '',
          mobile: '',
          // isuser:0,//用户(0：商户,1：管理员）
          name: '',
          password: '',
          sex: 1,//性别（1：男 2：女）
          username: '',
          birthday: ''
        }
        this.dialogStatus = true
      },
      queryRoleData() {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          keywords: ''
        }
        this.allRoles = []
        roleList(params).then((res) => {
          this.allRoles = res.values
        }).catch(error => {

        })
      },
      //关闭弹框调用的方法
      dalogClosed() {
        this.dialogStatus = false
      },
      updateClick(row) {
        this.type = 2
        this.selectRow = row
        this.userObject = row
        this.dialogStatus = true
      },
      deleteClick(row) {
        this.selectRow = row
        const vm = this
        this.$confirm('确认删除改用户么？', '确定删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser(vm.selectRow.id).then((res) => {
            vm.$message({type: 'success', message: '操作成功'})
            vm.isShowDesignArea = false
            vm.queryTableData()
          }).catch((err) => {

          })
        }).catch(() => {

        });
      },
      commitClick() {
        //提交
        this.dialogStatus = false
        if (this.type == 1) {
          delete this.userObject.id
        }
        addUpdateUser(this.userObject).then((res) => {
          this.$message({type: 'success', message: '操作成功'})
          this.queryTableData()
        }).catch((err) => {

        })
      },
      giveRole(row) {
        this.selectRow = row
        this.isShowDesignArea = true
        if (row.roleId) {
          this.defaultChecks = row.roleId.split(',')
        } else {
          this.defaultChecks = []
        }
        this.queryRoleData()
      }
    }
  }
</script>

<style scoped>

</style>
<style>
  .user .dialog-form {
    display: flex;
    align-items: center;
    margin-top: 10px;
  }

  .user .dialog-form .from-title {
    width: 70px;
    margin-right: 10px;
  }

  .user .dialog-form .from-title .from-title-i {
    color: red;
  }

  .user .dialog-form .el-form-item {
    flex: 1;
    margin-bottom: 0px;
  }

  .top-area {
    margin-bottom: 20px;
  }
</style>

